// src-tauri/src/content_verification.rs
use ring::signature::{self, KeyPair, Ed25519KeyPair};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use base64; // 添加base64导入

use crate::reputation_system::ReputationSystem;

#[derive(Serialize, Deserialize, Clone)]
pub struct ContentMetadata {
    pub file_hash: String,
    pub author_id: String,
    pub timestamp: u64,
    pub content_type: String, // "math_pdf", "python_script", etc.
    pub description: String,
    pub signature: String,
    pub reputation_score: f64,
}

pub struct ContentVerification {
    trusted_authors: HashMap<String, String>, // author_id -> public_key
    content_whitelist: HashMap<String, ContentMetadata>,
    reputation_system: ReputationSystem,
}

impl ContentVerification {
    pub fn new() -> Self {
        let mut trusted = HashMap::new();
        // 添加初始可信作者
        trusted.insert(
            "official_math_course".to_string(),
            "official_public_key_here".to_string()
        );
        
        Self {
            trusted_authors: trusted,
            content_whitelist: HashMap::new(),
            reputation_system: ReputationSystem::new(),
        }
    }
    
    pub fn verify_content_signature(
        &self, 
        metadata: &ContentMetadata, 
        content_data: &[u8]
    ) -> bool {
        // 验证作者是否可信
        let public_key = match self.trusted_authors.get(&metadata.author_id) {
            Some(key) => key,
            None => return false,
        };
        
        // 验证文件哈希
        let computed_hash = self.compute_hash(content_data);

        if computed_hash != metadata.file_hash {
            return false;
        }
        
        // 验证数字签名
        self.verify_signature(metadata, public_key)
    }
    
    // 验证数字签名
    fn verify_signature(&self, metadata: &ContentMetadata, public_key: &str) -> bool {
        // 将签名字符串解码为字节数组
        let signature_bytes = match base64::decode(&metadata.signature) {
            Ok(bytes) => bytes,
            Err(_) => return false,
        };
        
        // 将公钥字符串解码为字节数组
        let public_key_bytes = match base64::decode(public_key) {
            Ok(bytes) => bytes,
            Err(_) => return false,
        };
        
        // 创建要签名的数据（文件哈希 + 作者ID + 时间戳）
        let mut data_to_sign = metadata.file_hash.as_bytes().to_vec();
        data_to_sign.extend_from_slice(metadata.author_id.as_bytes());
        data_to_sign.extend_from_slice(&metadata.timestamp.to_be_bytes());
        
        // 使用Ed25519算法验证签名
        let public_key = signature::UnparsedPublicKey::new(&signature::ED25519, &public_key_bytes);
        
        // 验证签名
        match public_key.verify(&data_to_sign, &signature_bytes) {
            Ok(_) => true,
            Err(_) => false,
        }
    }
    
    // 计算内容的哈希值
    fn compute_hash(&self, content_data: &[u8]) -> String {
        // 这里简单示例使用 base64 编码作为哈希，实际应用中应该使用更安全的哈希算法
        base64::encode(content_data)
    }
    
    pub fn add_trusted_author(&mut self, author_id: String, public_key: String) {
        self.trusted_authors.insert(author_id, public_key);
    }
    
    pub fn is_content_approved(&self, file_hash: &str) -> bool {
        self.content_whitelist.contains_key(file_hash)
    }
    
    pub fn approve_content(&mut self, metadata: ContentMetadata) {
        self.content_whitelist.insert(metadata.file_hash.clone(), metadata);
    }
}